package com.leff.cards;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

import com.leff.cards.entity.QueryCard;
import com.leff.cards.entity.ResponseCard;
import com.leff.cards.request.RequestResult;

@SuppressWarnings("serial")
public class Cards_ServerServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(Cards_ServerServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setContentType("text/plain");
		
		log.info("I WANT TO SEE A LOG!");
		log.info("CAN I PLEASE SEE A LOG?");
//		System.out.println("ONLY LOGGING HERE? OR SOMETHING?");
		
		String query = req.getQueryString();
		query = URLDecoder.decode(query, "UTF-8");
		
		Dictionary dict = parseQueryString(query);
		
		String cmd = (String)dict.get("cmd");
		
		if("ALL_RESPONSE_CARDS".equals(cmd)) {
			
			ArrayList<ResponseCard> cards = StoreWrapper.getAllResponseCards();
			for(ResponseCard RC : cards) {
				resp.getWriter().println(RC.getText());
			}
			return;
		}
		if("ALL_QUERY_CARDS".equals(cmd)) {
			
			ArrayList<QueryCard> cards = StoreWrapper.getAllQueryCards();
			for(QueryCard QC : cards) {
				resp.getWriter().println(QC.getText());
			}
			return;
		}
		
		String[] commands = cmd.split(",");
		
		HashMap<String, Object> obj = new HashMap<String, Object>();
		for(String command : commands) {
			RequestResult result = ResponseFactory.parseCommandParameters(command, dict);
			obj.put(command, result.getJson());
		}
		String result = JSONObject.toJSONString(obj);
		
		resp.getWriter().println(result);
	}
	
	private static Dictionary parseQueryString(String query) {
		
		Dictionary dict = new Dictionary();
		
		if(query == null || query.length() == 0) {
			return dict;
		}
		
		String[] pairs = query.split("&");
		for(String pair : pairs) {
			
			String[] vals = pair.split("=");
			dict.put(vals[0], vals[1]);
		}
		
		return dict;
	}
}
